'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 过滤敏感词汇
 * @author sundbcn@gmail.com (sun debing)
 */

var dataApi = require('../libs/dataApi');
var _ = require('lodash');

var sensitive_filter = [];
var sensitive_check = [];

/**
 * 过滤聊天频道敏感词汇
 * @param {[type]} msg [description]
 */
exports.filter = function (msg) {
    _loadSensitiveWord();
    var content = msg;

    _.each(sensitive_filter, function (filter) {
        var reg_expr = filter.reg_expr;
        var check = reg_expr.test(content);
        var replace_sting = '';
        if (check) {
            content = content.replace(reg_expr, filter.to_str);
        }
    });
    return content;
};

/**
 * 检测创建名字敏感词汇
 * @param {[type]} msg [description]
 */
exports.detect = function (name) {
    _loadSensitiveWord();
    var detect_result = true;
    _.each(sensitive_check, function (check) {
        var reg_expr = check.reg_expr;
        if (reg_expr.test(name)) {
            detect_result = false;
            return false;
        }
    });
    return detect_result;
};

var _loadSensitiveWord = function () {
    if (sensitive_filter.length > 0) {
        return;
    }
    sensitive_filter = [];
    sensitive_check = [];

    dataApi.sensitive_word.any(function (item) {
        var word = item.des;
        var len = word.length;
        if (!word || len === 0) {
            return false;
        }
        var expr_str = word.replace(/\(/g, '\\(').replace(/\)/g, '\\)').replace(/\//g, '\\/').replace(/\*/g, '\\*');
        var reg_expr = new RegExp(expr_str, 'gm');
        var replace_string = '';
        for (var i = 0; i < len; i++) {
            replace_string += '*';
        }

        // 暂时采用字符串，避免直接用正则带来的问题
        sensitive_filter.push({
            id: item.id,
            reg_expr: reg_expr,
            to_str: replace_string
        });
        sensitive_check.push({
            id: item.id,
            reg_expr: new RegExp(expr_str)
        });
    });
};
